package com.liuzy.family.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liuzy.family.entity.PersonEntity;
import com.liuzy.family.mapper.PersonEntityMapper;
import com.liuzy.family.util.StrKit;

@Controller
@RequestMapping(value = "/family", method = RequestMethod.POST)
public class FamilyController extends BaseController {

	@Autowired
	private PersonEntityMapper personEntityMapper;

	@RequestMapping("/tree")
	@ResponseBody
	public Object tree(Integer id) {
		if (id == null) {
			return render("error");
		}
		PersonEntity me = personEntityMapper.selectByPrimaryKey(id);
		if (me == null) {
			return render("error");
		}
		if (!StrKit.isBlank(me.getBabaId())) {
			PersonEntity baba = personEntityMapper.selectByPrimaryKey(StrKit.firstId(me.getBabaId()));
			if (baba != null)
				return render(personHtml(baba));
		}
		return render(personHtml(me));
	}

	public String personHtml(PersonEntity p) {
		String html = "<li><a><b>" + p.getName() + "</b> ";
		if (!StrKit.isBlank(p.getSpouseId())) {
			PersonEntity se = personEntityMapper.selectByPrimaryKey(StrKit.firstId(p.getSpouseId()));
			if (se != null)
				html += se.getName();
		}
		html += "</a>";
		List<PersonEntity> childs = null;
		if ("M".equals(p.getSex()))
			childs = personEntityMapper.findChildsByBabaId("" + p.getId());
		else
			childs = personEntityMapper.findChildsByMamaId("" + p.getId());
		if (childs != null && !childs.isEmpty()) {
			html += "<ul>";
			for (PersonEntity child : childs) {
				html += personHtml(child);
			}
			html += "</ul>";
		}
		return html += "</li>";
	}

}
